package com.allinpay.trans.bizroute;

import com.allinpay.bizroute.genproto.ChkRouteSvcGrpc;
import com.allinpay.bizroute.genproto.MerchantTerm;
import com.allinpay.bizroute.genproto.RouteRule;
import com.allinpay.trans.bean.TransRouteRule;
import com.allinpay.trans.bean.TransRouteRuleDetail;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName BizRouteCli
 * @Description BizRouteCli module client
 * @Author richard
 * @Date 2021/12/16 9:08 AM
 */
// TODO: 2021/12/16  client 能否纳入spring管理，纳入管理是否有线程问题，是否有并发问题，待确认 
@Slf4j
@Component
public class BizRouteCli
{
    /**
     * 与客户端的链路
     */
    private  ManagedChannel channel;

    /**
     * 服务终端
     */
    private  ChkRouteSvcGrpc.ChkRouteSvcBlockingStub chkRouteSvcBlockingStub;

    //本地测试使用ip + 端口，或者host+端口
    //这里可以使用isito的hosts，虚拟服务
    //本机
//    private    String host = "127.0.0.1";

    @Value("${yunmis.grpc.bizroute.host}")
    private String host;

    @Value("${yunmis.grpc.bizroute.port}")
    private  Integer port  ;


//    public BizRouteCli(String host, int port) {
    @PostConstruct
    public void BizRouteCliStart() {
        //usePlaintext表示明文传输，否则需要配置ssl
        //channel  表示通信通道

        // TODO: 2021/12/16 需要确认同步和异步 
        // TODO: 2021/12/16 需要确认并发问题 
        channel = ManagedChannelBuilder
                //forAddress确认可用
//                .forAddress(host, port)
                //试试这个
                .forTarget(host+ ":" +port)
                .usePlaintext()
                .build();
        chkRouteSvcBlockingStub = ChkRouteSvcGrpc.newBlockingStub(channel);
        //添加一个系统关闭的钩子函数
        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            try {
                this.shutdown();
            } catch (InterruptedException e) {
                log.error("biz route client shutdown:", e);
            }
        }));
        log.info("Biz Route client start,{},{}", host,port);

    }

    public void shutdown() throws InterruptedException {

        //5秒等待关闭
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }


    public TransRouteRule callBizRouteSvc(String mcd, String tcd){

        log.info("transaction call bizroute service,mcd:{}, tcd:{}", mcd, tcd);

        MerchantTerm merchantTerm = MerchantTerm
                .newBuilder()
                .setMcd(mcd)
                .setTcd(tcd)
                .build();
        RouteRule routeRule = chkRouteSvcBlockingStub.chkByMchtTerm(merchantTerm);

        return transProto2Bean(routeRule);

    }

    private  TransRouteRule transProto2Bean(RouteRule routeRule){

        TransRouteRule transRouteRule = new TransRouteRule();
        TransRouteRuleDetail transRouteRuleDetail = new TransRouteRuleDetail();
        transRouteRuleDetail.setNum(routeRule.getDetail().getNum());
        transRouteRuleDetail.setName(routeRule.getDetail().getName());

        transRouteRule.setRuleDetail(transRouteRuleDetail);
        transRouteRule.setRspCd(routeRule.getRspCd());

        log.info("transRouteRule rsp:{}", transRouteRule.toString());
        return transRouteRule;
    }

}
